package com.ruoyi.web.controller.guomao;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IGmWaterRateService;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 水费管理
 *
 */
@Controller
@RequestMapping("/guomao/waterRateManagement")
public class GmWaterRateController extends BaseController
{
    private String prefix = "propertys/guomao/waterRateManagement";

    @Autowired
    private IGmWaterRateService gmWaterRateService;

    @GetMapping()
    public String waterRateManagement(ModelMap modelMap)
    {
        return prefix + "/main";
    }

    /**
     * 列表查询
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(GmWaterRate gmWaterRate)
    {
        startPage();
        List<GmWaterRate> gmWaterRateList = gmWaterRateService.getGmWaterRateList(gmWaterRate);
        return getDataTable(gmWaterRateList);
    }


    /**
     * 抄表信息添加
     */
    @GetMapping("/add")
    public String toAdd(ModelMap modelMap)
    {
        return prefix + "/add";
    }
    /**
     * 抄表信息添加保存
     */
    @PostMapping("/addSave")
    @ResponseBody
    public AjaxResult addSave(GmWaterRate gmWaterRate){
        try {
            GmWaterRate gmWr = gmWaterRateService.selectWaterRateByFloorAndEtldt(gmWaterRate);
            if(gmWr!=null&&!gmWr.getAmmeterId().equals(gmWaterRate.getAmmeterId())){
                return AjaxResult.error("该月份下已有抄表记录");
            }
            int i = gmWaterRateService.insertWaterRate(gmWaterRate);
            if(i>0){
                return AjaxResult.success();
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("新增失败："+e.getMessage());
        }
        return AjaxResult.error("保存失败");
    }
    /**
     * 抄表信息修改
     */
    @GetMapping("/edit/{ammeterId}")
    public String toEdit(@PathVariable("ammeterId") String ammeterId, ModelMap modelMap)
    {
        GmWaterRate gmWaterRate = gmWaterRateService.getWaterRateById(ammeterId);
        modelMap.put("gmWaterRate",gmWaterRate);
        return prefix + "/edit";
    }

    /**
     * 抄表信息修改保存
     */
    @Log(title = "水费管理", businessType = BusinessType.UPDATE)
    @PostMapping("/editSave")
    @ResponseBody
    public AjaxResult editSave(GmWaterRate gmWaterRate){
        return toAjax(gmWaterRateService.updateWaterRate(gmWaterRate));
    }

    /**
     * 抄表信息删除
     */
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids){
        try {
            int i = gmWaterRateService.removeWaterRate(ids);
            if(i>0){
                return AjaxResult.success();
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("删除失败："+e.getMessage());
        }
        return AjaxResult.error("删除失败");
    }
    /**
     * 导入抄表数据
     */
    @Log(title = "水费管理", businessType = BusinessType.IMPORT)
//    @RequiresPermissions("property:elecCost:import")
    @PostMapping("/importExcel")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
//        ExcelUtil<GmWaterRate> util = new ExcelUtil<>(GmWaterRate.class);
//        List<GmWaterRate> lists = util.importExcel(file.getInputStream());
        //校验数据
//        String message =gmWaterRateService.importWaterRate(lists,updateSupport);
//        return AjaxResult.success(message);

        ExcelUtil<GmWaterRateExcel> util = new ExcelUtil<>(GmWaterRateExcel.class);
        List<GmWaterRateExcel> lists = util.importExcel(file.getInputStream());
        SysUser sysUser = ShiroUtils.getSysUser();
        //校验数据
        String res = gmWaterRateService.validateDatas(lists);
        if (StringUtils.isNotBlank(res)){
            return AjaxResult.error(res);
        }
//        仅当没有错误信息时才会执行导入操作
        String message =gmWaterRateService.importRelations(lists,updateSupport,sysUser);

        return AjaxResult.success(message);
    }

    /**
     * 导入抄表数据模板
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<GmWaterRateExcel> util = new ExcelUtil<GmWaterRateExcel>(GmWaterRateExcel.class);
        return util.importTemplateExcel("抄表信息数据");
    }

    /**
     * 按月抄表导出
     */
//    @RequiresPermissions("guomao:waterRateManagement:export")
    @Log(title = "抄表导出", businessType = BusinessType.EXPORT)
    @PostMapping("/allExport")
    @ResponseBody
    public AjaxResult export(@Param("etldt")String etldt) {
        List<GmWaterRate> list = gmWaterRateService.selectWaterCostByEtldt(etldt);
        ExcelUtil<GmWaterRate> util = new ExcelUtil(GmWaterRate.class);
        return util.exportExcel(list, "水表数据");
    }

    /**
     * 导出水费单位信息列表
     */
    @Log(title = "单位导出", businessType = BusinessType.EXPORT)
    @PostMapping("/leaderExport")
    @ResponseBody
    public AjaxResult leaderExport(@Param("etldt")String etldt)
    {
        List<GmWaterRate> list = gmWaterRateService.selectWaterCostByEtldt(etldt);
        List<GmWaterCost> exportInfos = new ArrayList<>();
        Set nameSet = new HashSet();
//        统计公司信息
        for (int i = 0;i<list.size();i++)
        {
            nameSet.add(list.get(i).getUnitName());
        }
        List<String> nameList = new ArrayList(nameSet);
        for (int i = 0;i<nameList.size();i++){
            exportInfos.add(i,new GmWaterCost());
            List<GmWaterRate> listForName = gmWaterRateService.selectWaterCostByUName(nameList.get(i));
            exportInfos.get(i).setUnitName(nameList.get(i));
            exportInfos.get(i).setProjectName(listForName.get(0).getProjectName());
            exportInfos.get(i).setEtldt(listForName.get(0).getEtldt());
            double degree = 0,elecTotalPrice = 0;
            for (int j = 0;j<listForName.size();j++){
                degree += listForName.get(j).getDegree();
                elecTotalPrice += listForName.get(j).getAmountMoney();
            }
            exportInfos.get(i).setDegree(degree);
            exportInfos.get(i).setAmountMoney(elecTotalPrice);
        }
        ExcelUtil<GmWaterCost> util = new ExcelUtil<GmWaterCost>(GmWaterCost.class);
        return util.exportExcel(exportInfos, "单位"+etldt+"水表");
    }

}
